<template>
  <div class="encasement-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 装箱管理</p>
            <h2 class="breadcrumb-heading">装箱管理</h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item>装箱管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="search-card">
      <div class="search-card__header">
        <h3>高级筛选</h3>
        <span>支持关键字、客户与日期组合查询</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="装箱单">
          <el-input
            v-model="searchForm.packingListKeyword"
            placeholder="请输入装箱单编号或名称"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="客户信息">
          <el-input
            v-model="searchForm.customerKeyword"
            placeholder="请输入客户名称或编号"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="装箱日期">
          <el-date-picker
            v-model="searchForm.packingDate"
            type="date"
            placeholder="请选择装箱日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            class="search-input"
          >
            <template #prefix-icon>
              <el-icon><Calendar /></el-icon>
            </template>
          </el-date-picker>
        </el-form-item>
        <el-form-item class="search-actions">
          <el-button :icon="RefreshLeft" @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            :loading="loading"
            :icon="Search"
            @click="handleSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <div class="stats-grid">
      <div
        v-for="item in statsCards"
        :key="item.key"
        class="stats-card"
        :class="item.type"
      >
        <div class="stats-icon-box">
          <el-icon><component :is="item.icon" /></el-icon>
        </div>
        <div class="stats-content">
          <p class="stats-label">{{ item.label }}</p>
          <p class="stats-value">{{ item.value }}</p>
          <p class="stats-desc">{{ item.desc }}</p>
        </div>
      </div>
    </div>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div>
          <h3>装箱列表</h3>
          <p>
            共 {{ pagination.totalCount }} 条数据，当前第
            {{ pagination.pageIndex }}/{{ totalPages }} 页
          </p>
        </div>
        <div class="table-header__actions">
          <el-button type="primary" plain :icon="Plus" @click="handleAdd"
            >新增</el-button
          >
          <el-button
            type="danger"
            plain
            :icon="Delete"
            @click="handleBatchDelete"
            >删除</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        border
        highlight-current-row
        header-row-class-name="encasement-table-header-row"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          width="60"
          :index="getIndex"
        />
        <el-table-column
          prop="packingListName"
          label="装箱单名称"
          min-width="200"
        >
          <template #default="{ row }">
            <div class="name-cell">
              <strong>{{ row.packingListName || "未命名装箱单" }}</strong>
              <el-tag
                v-if="row.packingListNo"
                size="small"
                effect="plain"
                type="info"
                >{{ row.packingListNo }}</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="packingListNo"
          label="装箱单编号"
          min-width="150"
        />
        <el-table-column prop="packingDate" label="装箱日期" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.packingDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="salesOrderNo" label="订单编号" min-width="150" />
        <el-table-column prop="state" label="装箱状态" width="110">
          <template #default="{ row }">
            <el-tag
              :type="
                row.state === 2
                  ? 'success'
                  : row.state === 1
                  ? 'info'
                  : 'warning'
              "
              effect="light"
            >
              {{
                row.state === 2
                  ? "执行完成"
                  : row.state === 1
                  ? "进行中"
                  : "未执行"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" min-width="140">
          <template #default="{ row }">
            {{
              row.customerName ||
              row.customer_name ||
              row.customerId ||
              "未填写"
            }}
          </template>
        </el-table-column>
        <el-table-column label="客户编号" min-width="120">
          <template #default="{ row }">
            {{ row.customerCode || row.customer_code || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="boxLength"
          label="箱子长度(CM)"
          min-width="130"
        />
        <el-table-column prop="boxWidth" label="箱子宽度(CM)" min-width="130" />
        <el-table-column
          prop="boxHeight"
          label="箱子高度(CM)"
          min-width="130"
        />
        <el-table-column prop="netWeight" label="净重(KG)" min-width="110">
          <template #default="{ row }">
            <el-tag
              :type="Number(row.netWeight) > 50 ? 'danger' : 'success'"
              effect="light"
              disable-transitions
              >{{ row.netWeight || "-" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="标记为完成" placement="top">
              <el-button
                type="success"
                link
                size="small"
                @click="handleComplete(row)"
                >完成</el-button
              >
            </el-tooltip>
            <el-tooltip content="执行当前装箱单" placement="top">
              <el-button
                type="primary"
                link
                size="small"
                @click="handleExecute(row)"
                >执行</el-button
              >
            </el-tooltip>
            <el-tooltip content="删除装箱单" placement="top">
              <el-button
                type="danger"
                link
                size="small"
                @click="handleDelete(row)"
                >删除</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <el-icon class="empty-icon"><Box /></el-icon>
            <p>暂无装箱数据</p>
            <el-button type="primary" link @click="handleAdd"
              >立即创建装箱单</el-button
            >
          </div>
        </template>
      </el-table>
      <div class="table-pagination">
        <div style="display: flex; align-items: center; gap: 8px">
          <el-button
            size="small"
            @click="gotoFirst"
            :disabled="pagination.pageIndex === 1"
            >首页</el-button
          >
          <el-button
            size="small"
            @click="gotoPrev"
            :disabled="pagination.pageIndex === 1"
            >上一页</el-button
          >
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[3, 5, 10, 25]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            size="small"
            @click="gotoNext"
            :disabled="pagination.pageIndex >= totalPages"
            >下一页</el-button
          >
          <el-button
            size="small"
            @click="gotoLast"
            :disabled="pagination.pageIndex >= totalPages"
            >尾页</el-button
          >
        </div>
      </div>
    </el-card>
  </div>

  <!-- 新增/编辑对话框 -->
  <EncasementAdd
    ref="addDialogRef"
    v-model="showAddDialog"
    @success="handleAddSuccess"
  />
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  Search,
  User,
  Calendar,
  Plus,
  Delete,
  DataLine,
  Histogram,
  CollectionTag,
  RefreshLeft,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import https from "@/Http/http";
import moment from "moment";
import EncasementAdd from "./EncasementAdd.vue";
import { useRouter } from "vue-router";

const router = useRouter();

onMounted(() => {
  loadEncasementList();
});

const tableData = ref<any[]>([]);
const loading = ref(false);

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const searchForm = reactive({
  packingListKeyword: "",
  customerKeyword: "",
  packingDate: "",
});

// 序号计算
const getIndex = (index: number) => {
  return (pagination.pageIndex - 1) * pagination.pageSize + index + 1;
};

// 日期格式化
const formatDate = (date: string | Date) => {
  if (!date) return "";
  return moment(date).format("YYYY-MM-DD");
};

// 总页数
const totalPages = computed(() =>
  Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize))
);

const stats = computed(() => {
  const list = tableData.value;
  const currentPage = list.length;
  const totalNetWeight = list.reduce(
    (sum, item) => sum + (Number(item.netWeight) || 0),
    0
  );
  const averageVolume =
    list.length > 0
      ? Math.round(
          list.reduce((sum, item) => {
            const length = Number(item.boxLength) || 0;
            const width = Number(item.boxWidth) || 0;
            const height = Number(item.boxHeight) || 0;
            return sum + length * width * height;
          }, 0) / list.length
        )
      : 0;

  return {
    currentPage,
    totalNetWeight: totalNetWeight.toFixed(1),
    averageVolume,
    heavyCases: list.filter((item) => Number(item.netWeight) > 50).length,
  };
});

const statsCards = computed(() => [
  {
    key: "currentPage",
    label: "本页装箱单",
    value: stats.value.currentPage,
    desc: `总计 ${pagination.totalCount} 单`,
    icon: CollectionTag,
    type: "is-blue",
  },
  {
    key: "netWeight",
    label: "本页净重合计",
    value: `${stats.value.totalNetWeight} kg`,
    desc: "净重求和",
    icon: DataLine,
    type: "is-green",
  },
  {
    key: "volume",
    label: "平均体积",
    value:
      stats.value.averageVolume > 0
        ? `${stats.value.averageVolume} cm³`
        : "暂无数据",
    desc: "按长宽高计算",
    icon: Histogram,
    type: "is-orange",
  },
  {
    key: "heavy",
    label: "重载装箱",
    value: `${stats.value.heavyCases} 单`,
    desc: "净重大于50kg",
    icon: Box,
    type: "is-red",
  },
]);

// 加载装箱列表
const loadEncasementList = () => {
  loading.value = true;
  const params: any = {
    PageIndex: pagination.pageIndex,
    PageSize: pagination.pageSize,
  };

  if (searchForm.packingListKeyword) {
    params.PackingListKeyword = searchForm.packingListKeyword;
  }

  if (searchForm.customerKeyword) {
    params.CustomerKeyword = searchForm.customerKeyword;
  }

  if (searchForm.packingDate) {
    params.PackingDate = searchForm.packingDate;
  }

  https.Reads.get("/Warehouse/EncasementList", { params })
    .then((res: any) => {
      if (res.data.code === 1) {
        tableData.value = res.data.data || [];
        pagination.totalCount = res.data.totalCount || 0;
        pagination.pageCount = res.data.pageCount || 0;
      } else {
        ElMessage.error(res.data.msg || "获取装箱列表失败");
        tableData.value = [];
        pagination.totalCount = 0;
      }
    })
    .catch((error: any) => {
      console.error("加载装箱列表失败:", error);
      ElMessage.error("获取装箱列表失败，请稍后重试");
      tableData.value = [];
      pagination.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 查询
const handleSearch = () => {
  pagination.pageIndex = 1;
  loadEncasementList();
};

// 重置
const handleReset = () => {
  searchForm.packingListKeyword = "";
  searchForm.customerKeyword = "";
  searchForm.packingDate = "";
  handleSearch();
};

// 每页条数改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  loadEncasementList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  loadEncasementList();
};

// 首页
const gotoFirst = () => {
  if (pagination.pageIndex !== 1) {
    pagination.pageIndex = 1;
    loadEncasementList();
  }
};

// 上一页
const gotoPrev = () => {
  if (pagination.pageIndex > 1) {
    pagination.pageIndex -= 1;
    loadEncasementList();
  }
};

// 下一页
const gotoNext = () => {
  if (pagination.pageIndex < totalPages.value) {
    pagination.pageIndex += 1;
    loadEncasementList();
  }
};

// 尾页
const gotoLast = () => {
  if (pagination.pageIndex !== totalPages.value) {
    pagination.pageIndex = totalPages.value;
    loadEncasementList();
  }
};

// 新增对话框
const showAddDialog = ref(false);
const addDialogRef = ref();

// 新增
const handleAdd = () => {
  showAddDialog.value = true;
};

// 新增成功回调
const handleAddSuccess = () => {
  loadEncasementList();
};

// 完成
const handleComplete = (row: any) => {
  ElMessageBox.confirm("确认要完成该装箱单吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage.success("完成操作待实现");
    })
    .catch(() => {});
};

// 执行
const handleExecute = (row: any) => {
  if (!row || !row.packingListNo) {
    ElMessage.warning("当前行缺少装箱单编号，无法执行装箱");
    return;
  }

  router.push({
    path: "/EncasementExecute",
    query: {
      packingListNo: row.packingListNo,
      packingListName: row.packingListName || "",
      salesOrderNo: row.salesOrderNo || "",
      customerName: row.customerId || "",
      customerCode: row.customerCode || "",
    },
  });
};

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认要删除该装箱单吗？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.put("/Warehouse/EncasementDelete", { id: row.packingListId })
        .then((res: any) => {
          if (res.data.code === 1) {
            ElMessage.success(res.data.msg || "删除成功");
            loadEncasementList();
          } else {
            ElMessage.error(res.data.msg || "删除失败");
          }
        })
        .catch((error: any) => {
          console.error("删除失败:", error);
          ElMessage.error("删除失败，请稍后重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 批量删除
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

const tableRowClassName = ({ row }: { row: any }) => {
  const isHeavy = Number(row.netWeight) > 50;
  return isHeavy ? "row-heavy" : "";
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的装箱单！");
    return;
  }

  const ids = multipleSelection.value.map((x) => x.packingListId);

  ElMessageBox.confirm(
    `确认要批量删除选中的${multipleSelection.value.length}条装箱单吗？`,
    "警告",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      https.Writes.delete("/Warehouse/EncasementDeletes", {
        data: { Ids: ids },
      })
        .then((res: any) => {
          if (res.data.code === 1) {
            ElMessage.success(res.data.msg || "批量删除成功");
            loadEncasementList();
          } else {
            ElMessage.error(res.data.msg || "批量删除失败");
          }
        })
        .catch((error: any) => {
          console.error("批量删除失败:", error);
          ElMessage.error("批量删除失败，请稍后重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

<style scoped>
.encasement-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-bottom: 12px;
}

.breadcrumb-card {
  border-radius: 12px;
  background: linear-gradient(135deg, #f5f9ff, #ffffff);
  border: none;
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.breadcrumb-icon {
  font-size: 28px;
  color: #409eff;
}

.breadcrumb-subtitle {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.breadcrumb-heading {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 8px 24px rgba(15, 35, 95, 0.06);
}

.search-card__header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 12px;
  color: #606266;
}

.search-card__header h3 {
  margin: 0;
  font-weight: 600;
  color: #303133;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.search-input {
  width: 240px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }
}

.search-actions {
  display: flex;
  gap: 8px;
}

.table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 8px 24px rgba(15, 35, 95, 0.06);
}

.table-header {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  flex-wrap: wrap;
  gap: 12px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.table-header p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 13px;
}

.table-header__actions {
  display: flex;
  gap: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 12px;
}

.stats-card {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 16px;
  border-radius: 16px;
  background: #fff;
  border: 1px solid #f0f2f5;
  box-shadow: 0 12px 30px rgba(15, 35, 95, 0.05);
}

.stats-icon-box {
  width: 46px;
  height: 46px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}

.stats-card.is-blue .stats-icon-box {
  background: linear-gradient(135deg, #5ca0ff, #637afe);
}

.stats-card.is-green .stats-icon-box {
  background: linear-gradient(135deg, #4bc0c8, #2c9f8d);
}

.stats-card.is-orange .stats-icon-box {
  background: linear-gradient(135deg, #ff9a44, #ff6a88);
}

.stats-card.is-red .stats-icon-box {
  background: linear-gradient(135deg, #ff6b6b, #ff8e53);
}

.stats-label {
  margin: 0;
  font-size: 13px;
  color: #909399;
}

.stats-value {
  margin: 4px 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.stats-desc {
  margin: 0;
  font-size: 12px;
  color: #a0a3a8;
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.encasement-table-header-row th {
  background: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

.row-heavy {
  --el-table-tr-bg-color: #fff9f2;
}

.table-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.empty-state {
  padding: 40px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  color: #dcdfe6;
}
</style>
